package com.example.testanimation.objectanimation;

import android.animation.AnimatorSet;
import android.animation.ObjectAnimator;
import android.animation.TypeEvaluator;
import android.annotation.SuppressLint;
import android.app.Activity;
import android.content.Context;
import android.graphics.Canvas;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;

import com.nova.scenic.projectlibs.util.debug.MyLog;
import com.scenic.rd_android.R;

public class CustomObjectEvent extends Activity{
	private static final String TAG = CustomObjectEvent.class.getSimpleName();
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.animation_cloning);
		ViewGroup group = (ViewGroup) findViewById(R.id.container);
		final MyView view = new MyView(this);
		group.addView(view);
		findViewById(R.id.startButton).setOnClickListener(new OnClickListener(
				) {
			@Override
			public void onClick(View v) {
				view.startAnimation();;
				
			}
		});
	}
	
	class ShapeXYHodle {
		ShapeHolder XY;
		public ShapeXYHodle(ShapeHolder xy) {
			this.XY = xy;
		}
		public void setXY(ShapeHolder xy){
			this.XY.setX(xy.getX());
			this.XY.setY(xy.getY());
		}
	}
	
	
	@SuppressLint("NewApi")
	class MyView extends View {


		AnimatorSet animator;
		
		ShapeHolder shape = new ShapeHolder();
		ShapeXYHodle xyhodler;
		public MyView(Context context) {
			super(context);
			xyhodler = new ShapeXYHodle(shape);
		}
		
		
		void startAnimation(){
			animator = createAnimation();
			animator.start();
		}

		@Override
		protected void onDraw(Canvas canvas) {
			super.onDraw(canvas);
			canvas.save();
			canvas.translate(shape.getX(), shape.getY());
			shape.getShape().draw(canvas);
			canvas.restore();
			
			
			invalidate();
		}
		

		private AnimatorSet createAnimation() {
			if(animator == null){
				animator = new AnimatorSet();
				ObjectAnimator animator_ = ObjectAnimator.ofObject(xyhodler, "xY", 
				new TypeEvaluator() {
					@Override
					public Object evaluate(float fraction, Object startValue, Object endValue) {
						MyLog.d(TAG, "fraction " + fraction + " startValue " + startValue + " endValue " + endValue);
						return new ShapeHolder().setX(500).setX(500);
					}
				},
				//这里的参数最重要的是看xyhodler 的 setXY 的参数是什么，和 setXY的参数保持一致
				new ShapeHolder().setX(100).setY(100), 
				new ShapeHolder().setX(600).setY(600));
				
				animator_.setDuration(500);
				animator_.start();
				animator.play(animator_);
			}
			return animator;
		}
		
	}
	
}
